package com.hu.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hu.auth.common.aop.Verify;
import com.hu.auth.common.result.R;
import com.hu.auth.model.Menu;
import com.hu.auth.model.po.MenuAddPo;
import com.hu.auth.service.MenuService;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Api(tags = "菜单模块")
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Resource
    MenuService menuService;

    @Verify(key = "bnt.sysMenu.list")
    @GetMapping("/tree")
    public R tree() {
        return R.ok(menuService.tree());
    }

    @Verify(key = "bnt.sysMenu.list")
    @GetMapping("/getById/{id}")
    public R getById(@PathVariable Long id) {
        if (id < 0) {
            return R.fail().message("参数错误");
        }
        return R.ok(menuService.getById(id));
    }

    @Verify(key = "bnt.sysMenu.add")
    @PostMapping("/add")
    public R add(@RequestBody @Validated MenuAddPo po) {
        if (po.getId() != null) {
            return R.fail().message("参数错误");
        }
        if (menuService.count(new LambdaQueryWrapper<Menu>().eq(Menu::getName, po.getName())) > 0) {
            return R.fail().message("角色名出现重复");
        }
        Menu menu = new Menu();
        BeanUtils.copyProperties(po, menu);
        menuService.save(menu);
        return R.ok();
    }

    @Verify(key = "bnt.sysMenu.update")
    @PostMapping("/update")
    public R update(@RequestBody @Validated MenuAddPo po) {
        if (po.getId() == null) {
            return R.fail().message("参数错误");
        }
        if (menuService.count(new LambdaQueryWrapper<Menu>()
                .ne(Menu::getId, po.getId())
                .eq(Menu::getName, po.getName())) > 0) {
            return R.fail().message("角色名出现重复");
        }
        Menu Menu = new Menu();
        BeanUtils.copyProperties(po, Menu);
        menuService.updateById(Menu);
        return R.ok();
    }

    @Verify(key = "bnt.sysMenu.remove")
    @DeleteMapping("/removeById/{id}")
    public R removeById(@PathVariable Long id) {
        if (id < 1) {
            return R.fail().message("参数错误");
        }
        menuService.removeById(id);
        return R.ok();
    }

}
